from models.models import User, db
from flask_jwt_extended import create_access_token

class AuthController:
    @staticmethod
    def register(data):
        username = data.get('username')
        password = data.get('password')
        age = data.get('age')
        gender = data.get('gender')
        ethnicity = data.get('ethnicity')
        mandarin_level = data.get('mandarin_level')
        
        # Check if username already exists
        if User.query.filter_by(username=username).first():
            return {'code': 400, 'message': '用户名已存在', 'data': None}
        
        # Create new user
        user = User(
            username=username,
            age=age,
            gender=gender,
            ethnicity=ethnicity,
            mandarin_level=mandarin_level
        )
        user.set_password(password)
        
        # Save to database
        db.session.add(user)
        db.session.commit()
        
        return {
            'code': 200,
            'message': '注册成功',
            'data': {
                'id': user.id,
                'username': user.username
            }
        }
    
    @staticmethod
    def login(data):
        username = data.get('username')
        password = data.get('password')
        
        # Find user by username
        user = User.query.filter_by(username=username).first()
        
        if not user or not user.check_password(password):
            return {'code': 401, 'message': '用户名或密码错误', 'data': None}
        
        # Generate token - 只用id作为identity，role放到additional_claims
        token = create_access_token(identity=str(user.id), additional_claims={"role": user.role})
        
        return {
            'code': 200,
            'message': '登录成功',
            'data': {
                'token': token,
                'user': user.to_dict()
            }
        }
    
    @staticmethod
    def update_user(user_id, data):
        user = User.query.get(user_id)
        
        if not user:
            return {'code': 404, 'message': '用户不存在', 'data': None}
        
        # Update fields if provided
        if 'username' in data and data['username'] != user.username:
            # Check if new username is already taken
            if User.query.filter_by(username=data['username']).first():
                return {'code': 400, 'message': '用户名已存在', 'data': None}
            user.username = data['username']
            
        if 'age' in data:
            user.age = data['age']
            
        if 'gender' in data:
            user.gender = data['gender']
            
        if 'ethnicity' in data:
            user.ethnicity = data['ethnicity']
            
        if 'mandarin_level' in data:
            user.mandarin_level = data['mandarin_level']
        
        # Save changes
        db.session.commit()
        
        return {
            'code': 200,
            'message': '更新成功',
            'data': user.to_dict()
        }
    
    @staticmethod
    def change_password(user_id, data):
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        user = User.query.get(user_id)
        
        if not user:
            return {'code': 404, 'message': '用户不存在', 'data': None}
        
        # Verify old password
        if not user.check_password(old_password):
            return {'code': 401, 'message': '原密码错误', 'data': None}
        
        # Set new password
        user.set_password(new_password)
        db.session.commit()
        
        return {
            'code': 200,
            'message': '密码修改成功',
            'data': None
        } 